<?php
namespace Framework\DiServices;

use Phalcon\Db\Adapter\Pdo\Mysql;
use Phalcon\Events\Manager;
use Phalcon\Logger\Adapter\File;
use StarCloud\Library\JaegerInject;
use Phalcon\Di;

class Db extends Mysql
{
    public $sqlLogs = [];
    /**
     * @var JaegerInject
     */
    protected $jaeger;
    public $shareSqlArr = 'shareSql';

    public function __construct($dbConfig)
    {
        $dbConfig['options'] = [
            // 中文 并且 fix 发4字节表情的bug
            \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8MB4'",
            // LIMIT参数绑定的bug
            \PDO::ATTR_EMULATE_PREPARES => false,
            \PDO::ATTR_STRINGIFY_FETCHES => false,
        ];

        parent::__construct($dbConfig);
        if (isset($dbConfig['logPath']) && !empty($dbConfig['logPath']) && file_exists($dbConfig['logPath'])) {
            $eventsManager = new Manager();
            $logger = new File($dbConfig['logPath']);
            $eventsManager->attach('db', function ($event, $connection) use ($logger) {
                if ($event->getType() == 'beforeQuery') {
                    $this->addSqlLogs($connection->getSQLStatement());
                    $logger->info($connection->getSQLStatement());
                }
            });

            $this->setEventsManager($eventsManager);
        }
    }

    public function addSqlLogs($sql)
    {
        try {
            $sqls = Di::getDefault()->get($this->shareSqlArr);
        } catch (\Exception $e) {
            $sqls = [];
        }
        $sqls[] = $sql;

        Di::getDefault()->setShared($this->shareSqlArr, function () use ($sqls) {
            return $sqls;
        });
    }
}
